package no.ntnu.fp.handlers;

import java.io.IOException;

import no.ntnu.fp.client.Client;
import no.ntnu.fp.client.exceptions.NetworkException;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.model.CalendarModel;
import no.ntnu.fp.model.DialogModel;
import no.ntnu.fp.model.LoggedInModel;
import no.ntnu.fp.model.LoggedInModel.LoginError;
import no.ntnu.fp.model.NoticeModel;
import no.ntnu.fp.net.co.Connection;

public class LogoutSuccessfulHandler implements Handler{
	private final LoggedInModel loggedInModel;
	private final CalendarModel calendarModel;
	private final DialogModel dialogModel;
	private final NoticeModel noticeModel; 
	private final Connection connection;
	
	public LogoutSuccessfulHandler(	LoggedInModel model,
									CalendarModel calendarModel,
									DialogModel dialogModel,
									NoticeModel noticeModel, 
													Connection connection) {
		this.loggedInModel = model;
		this.connection = connection;
		this.calendarModel = calendarModel;
		this.dialogModel = dialogModel;
		this.noticeModel = noticeModel;
	}

	@Override
	public void handleMessage(Message message) {
		try {
			this.connection.close();
		} catch (IOException e) {
			throw new NetworkException("Unable to disconnect connection", e);
		}
		
		this.calendarModel.clearModel();
//		this.dialogModel.clearModel();
		this.noticeModel.clearModel();
		
		this.loggedInModel.setLoggedIn(false, LoginError.INVALID_USER_CREDENTIALS);
		
		
		/* We don't really need this, as ReceiveWorker 
		 * should stop when connection is closed.
		 * Keeping it here just in case anyways ^_^; 
		 */
		Client.stopReceiveWorker();
	}
}
